package com.lagou.pay;

import com.lagou.db.FailedOrderDB;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import static com.lagou.constant.RabbitMqConstant.*;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Author: xunliu
 * @Date: 2021/01/24 11:15
 */
@RestController
public class PayController {

    @Autowired
    private AmqpTemplate rabbitmqTemplate;

    @PostMapping("/order/create")
    public void createOrder() {
        final String orderId = UUID.randomUUID().toString();
        rabbitmqTemplate.send(PAY_EXCHANGE, PAY_ROUTING_KEY, MessageBuilder.withBody(orderId.getBytes()).build());
    }

    @PostMapping("/order/pay")
    public String payOrder() {
        final Object resp = rabbitmqTemplate.receiveAndConvert(PAY_QUEUE);
        if (resp == null) {
            return PAY_FAIL_RESPONSE;
        } else {
            return PAY_SUCCESS_RESPONSE;
        }
    }

    @PostMapping("/order/overtime")
    public List<String> overtime() {
        final Message failOrder = rabbitmqTemplate.receive(PAY_FAIL_QUEUE);
        if (failOrder != null) {
            FailedOrderDB.failOrderSet.add(new String(failOrder.getBody()));
        }
        return new ArrayList<>(FailedOrderDB.failOrderSet);
    }
}
